#!/usr/local/bin/python
# -*- coding: utf-8 -*-

import datetime
from flask import Flask, url_for, request, session, render_template, redirect
from flaskext.sqlalchemy import SQLAlchemy
from json import dumps

from bompy import app
from utils import q, table, login_required, get2parameters, formtable, textinput, unitoptions, designoptions, typeoptions
from model import Design, BOM, Stock

db = SQLAlchemy(app)
Usercode=1

@app.route('/addstock')
@login_required
def addstock():
    form = (
    ("Product", designoptions("ID",types=[1,2,3,4,5])),
    ("Quantity", textinput("QU","1"))
    )
    f=formtable(form,action="_stock_db")
    return render_template("loadstock.html",f=f)


@app.route('/viewstock')
@login_required
def viewstock():
    t = table(["Design ID", "Description", "Quantity", "Bar Code", "state","Storage"])
    return render_template("viewstock.html",t=t)


@app.route('/_stock_search')
def stock_search():
    d={"aaData":[]}
    q = Stock.query.all()
    for i in q:
        d["aaData"].append(i.table())
    return dumps(d)    


@app.route('/_stock_db')
@get2parameters
def stock_db(ID, QU=1):
    QU = int(QU)
    if Design.getCurrent(ID).ID_Design_Type == 1:
        for i in range(QU):
            s = Stock()
            s.ID_Design=ID
            if Stock.query.filter_by(ID_Design = ID).first():
                s.Bar_Code = Stock.query.filter_by(ID_Design=ID).order_by(
                           db.desc(Stock.Bar_Code)).first().Bar_Code + 1
            else:
                s.Bar_Code=1        
            s.ID_State=1
            s.Quantity=1
            s.ID_Storage = 2
            s.Start_Date = datetime.datetime.today()
            s.User_Create = Usercode
            db.session.add(s)
            db.session.commit()
    else:
        s = Stock()
        s.ID_Design=ID
        s.Bar_Code=0
        s.ID_State=1
        s.Quantity = QU
        s.ID_Storage = 2
        s.Start_Date = datetime.datetime.today()
        s.User_Create = Usercode
        db.session.add(s)
        db.session.commit()
    
        
    return redirect(url_for('start_screen'))
    
